package com.sehgnheng.demo.modules.sys.oauth2;


import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Oauth2Filter extends AuthenticatingFilter {
    /**
     * 获得请求中的token
     * @return
     */
    @Override
    public AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse){
        //先从请求头部中获得token
       String token = this.getToken(servletRequest);
        if (StringUtils.isEmpty(token)){
            return null;
        }
        return new Oauth2Token(token);
    }
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        String token = this.getToken(servletRequest);
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        if(StringUtils.isEmpty(token)){
            HttpServletResponse response = (HttpServletResponse)servletResponse;
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        }
        return false;
    }



    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue){
        if (((HttpServletRequest)request).getMethod().equals(RequestMethod.OPTIONS.name())){
            return true;
        }
        return false;
    }

    /**
     * 从请求中获得token
     */
    public String getToken(ServletRequest servletRequest){
        HttpServletRequest request =  (HttpServletRequest)servletRequest;
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            //头部没有token，从参数中获得
            token = request.getParameter("token");
        }
        return token;
    }



}
